package com.itcodai.config.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.CustomizableThreadCreator;

import javax.annotation.Resource;
import java.util.concurrent.ThreadPoolExecutor;

//@Component
//@EnableScheduling
public class ThreadPoolMonitor {

    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolMonitor.class);

    @Resource
    //@Resource
    private ThreadPoolExecutor threadPoolExecutor;
    //private ThreadPoolTaskExecutor threadPoolExecutor;

    @Resource
    private CustomizableThreadCreator customizableThreadCreator;

    @Scheduled(fixedRate = 5000) // 每隔5秒执行一次
    public void monitorThreadPool() {
        logger.info("监控线程状态！");
        int activeCount = threadPoolExecutor.getActiveCount();
        int corePoolSize = threadPoolExecutor.getCorePoolSize();
        //int maxPoolSize = threadPoolExecutor.getMaximumPoolSize();
        //long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
        //long taskCount = threadPoolExecutor.getTaskCount();

        System.out.println("Active threads: " + activeCount);
        System.out.println("Core pool size: " + corePoolSize);
        //System.out.println("Max pool size: " + maxPoolSize);
        //System.out.println("Completed tasks: " + completedTaskCount);
        //System.out.println("Total tasks: " + taskCount);

        logger.info("prefix[{}], activeCount[{}]",
                customizableThreadCreator.getThreadNamePrefix(),
                activeCount
        );

        /*logger.info("prefix[{}], taskCount[{}], completedTaskCount[{}], activeCount[{}], queueSize[{}]",
                customizableThreadCreator.getThreadNamePrefix(),
                taskCount,
                completedTaskCount,
                activeCount
                ,threadPoolExecutor.getQueue().size()
        );*/

    }
}